package com.bcnapps.DemoGame;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;

public class Background extends SurfaceView {

	private SurfaceHolder holder;
	private BGDrawThread bgdt;
	
	//classes auxiliars
	private Nuvols nuvols;
	//control thread
	private boolean surfacecreated;
	private boolean threadrunning;
	//fons
	Paint fons;
	
	public Background(Context context) {
		super(context);
		init();
	}

	public Background(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public Background(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}
	
	private void init() {
		surfacecreated = false;
		threadrunning = false;
		holder = getHolder();
		holder.addCallback( new Callback() {
			
			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				stopthread();
				surfacecreated = false;
			}
			
			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				holder.setFormat(PixelFormat.RGBA_8888);
				
				fons = new Paint(); 
			    Shader shader = new LinearGradient(0,0,GV.Screen.metrics.widthPixels,GV.Screen.metrics.heightPixels,new int[]{0xFFA4D8FF,0xFF0031D2},null,Shader.TileMode.CLAMP);
			    fons.setShader(shader);  
				
				nuvols = new Nuvols(getResources());
				surfacecreated = true;
			}
			
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
				startthread();
			}
		});  
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawRect(0,0,getWidth(),getHeight(), fons);
		nuvols.actualitza();
		nuvols.draw(canvas);
	}
	
	public void startthread() {
		if(!surfacecreated) return;
		if(threadrunning) return;
		bgdt = new BGDrawThread(this);
		bgdt.setRunning(true);
		bgdt.start();
		threadrunning = true;
	}
	
	public void stopthread() {
		if(!surfacecreated) return;
		if(!threadrunning) return;
		boolean retry = true;
		while (retry) {
			try {
				bgdt.setRunning(false);
				bgdt.join();
				threadrunning = false;
				retry = false;
				
			} catch (InterruptedException e) {}
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return super.onTouchEvent(event);
	}
}
